//
// Created by 29108 on 2025/7/15.
//
#include "core_services/api_gateway/api_gateway.h"
#include "common/logger/logger.h"
#include "common/config/config_manager.h"

/**
 * @brief API网关基本使用示例
 * @details 演示如何创建、配置和启动API网关
 */
int main() {
    try {
        // 1. 初始化配置管理器
        auto& config_manager = common::config::ConfigManager::getInstance();
        config_manager.loadFromFile("../../../../config/api_gateway_config_example.yaml");

        // 2. 初始化日志系统
        common::logger::Logger::getInstance().initializeFromConfig();

        // 3. 创建API网关配置
        auto gateway_config = core_services::api_gateway::ApiGateway::Config::fromConfigManager();

        // 4. 创建API网关实例
        core_services::api_gateway::ApiGateway gateway(gateway_config);

        // 5. 添加认证服务路由
        LOG_DEBUG("开始配置认证服务路由...");

        // 认证API路由
        core_services::api_gateway::ServiceRoute auth_service_route;
        auth_service_route.service_name = "auth_service";
        auth_service_route.path_pattern = "/api/v1/auth/*";
        auth_service_route.methods = {"GET", "POST", "PUT", "DELETE", "OPTIONS"};
        auth_service_route.target_host = "localhost";
        auth_service_route.target_port = 8008;
        auth_service_route.target_path_prefix = "";  // 不去除前缀，直接转发
        auth_service_route.strip_path_prefix = false;  // 保持原始路径
        auth_service_route.timeout_ms = 30000;
        auth_service_route.retry_count = 3;
        auth_service_route.enable_circuit_breaker = true;
        auth_service_route.enable_rate_limiting = true;
        auth_service_route.match_type = core_services::api_gateway::ServiceRoute::MatchType::PREFIX;
        auth_service_route.enabled = true;
        auth_service_route.route_id = "auth_service_route";  // 添加路由ID

        LOG_DEBUG("认证服务路由配置: path=" + auth_service_route.path_pattern +
                 ", service=" + auth_service_route.service_name +
                 ", target=" + auth_service_route.target_host + ":" + std::to_string(auth_service_route.target_port));

        gateway.addServiceRoute(auth_service_route);
        LOG_INFO("认证服务路由已添加: " + auth_service_route.path_pattern);

        // ==================== 游戏认证路由（指向认证服务） ====================
        // 处理游戏登录、服务器发现等认证相关功能
        core_services::api_gateway::ServiceRoute game_auth_route;
        game_auth_route.service_name = "auth_service";  // 修复：使用与Auth Service注册时相同的服务名称
        game_auth_route.path_pattern = "/api/v1/game/*";
        game_auth_route.methods = {"GET", "POST", "PUT", "DELETE", "OPTIONS"};
        game_auth_route.target_host = "localhost";
        game_auth_route.target_port = 8008;  // 认证服务端口
        game_auth_route.target_path_prefix = "";  // 不去除前缀，直接转发
        game_auth_route.strip_path_prefix = false;  // 保持原始路径
        game_auth_route.timeout_ms = 30000;
        game_auth_route.retry_count = 3;
        game_auth_route.enable_circuit_breaker = true;
        game_auth_route.enable_rate_limiting = true;
        game_auth_route.match_type = core_services::api_gateway::ServiceRoute::MatchType::PREFIX;
        game_auth_route.enabled = true;
        game_auth_route.route_id = "game_auth_route";  // 添加路由ID
        game_auth_route.priority = 110;  // 设置优先级，低于认证服务

        LOG_DEBUG("游戏认证路由配置: path=" + game_auth_route.path_pattern +
                 ", service=" + game_auth_route.service_name +
                 ", target=" + game_auth_route.target_host + ":" + std::to_string(game_auth_route.target_port));

        gateway.addServiceRoute(game_auth_route);
        LOG_INFO("游戏认证路由已添加: " + game_auth_route.path_pattern);

        // ==================== Snake游戏服务路由 ====================
        // 处理具体的贪吃蛇游戏API
        core_services::api_gateway::ServiceRoute snake_game_route;
        snake_game_route.service_name = "snake_game_service";
        snake_game_route.path_pattern = "/api/v1/snake/*";
        snake_game_route.methods = {"GET", "POST", "PUT", "DELETE", "OPTIONS"};
        snake_game_route.target_host = "localhost";
        snake_game_route.target_port = 8084;  // Snake游戏服务端口
        snake_game_route.target_path_prefix = "";  // 不去除前缀，直接转发
        snake_game_route.strip_path_prefix = false;  // 保持原始路径
        snake_game_route.timeout_ms = 30000;
        snake_game_route.retry_count = 3;
        snake_game_route.enable_circuit_breaker = true;
        snake_game_route.enable_rate_limiting = true;
        snake_game_route.match_type = core_services::api_gateway::ServiceRoute::MatchType::PREFIX;
        snake_game_route.enabled = true;
        snake_game_route.route_id = "snake_game_route";
        snake_game_route.priority = 100;  // 设置优先级

        LOG_DEBUG("Snake游戏服务路由配置: path=" + snake_game_route.path_pattern +
                 ", service=" + snake_game_route.service_name +
                 ", target=" + snake_game_route.target_host + ":" + std::to_string(snake_game_route.target_port));

        gateway.addServiceRoute(snake_game_route);
        LOG_INFO("Snake游戏服务路由已添加: " + snake_game_route.path_pattern);

        LOG_INFO("所有服务路由配置完成");

        // 重要：对路由进行排序，确保高优先级路由优先匹配
        gateway.sortRoutes();
        LOG_INFO("路由排序完成，按优先级从高到低排列");

        // 验证路由配置
        auto all_routes = gateway.getAllRoutes();
        LOG_INFO("当前已配置的路由总数: " + std::to_string(all_routes.size()));
        for (const auto& route : all_routes) {
            LOG_INFO("路由: " + route.service_name + " " + route.path_pattern + " -> " +
                     route.target_host + ":" + std::to_string(route.target_port));
        }

        // 测试路由匹配
        LOG_INFO("测试路由匹配:");
        auto test_route = gateway.findRoute("POST", "/api/v1/auth/login");
        if (test_route) {
            LOG_INFO("✓ POST /api/v1/auth/login 匹配到路由: " + test_route->service_name);
        } else {
            LOG_ERROR("✗ POST /api/v1/auth/login 未找到匹配路由");
        }

        // 测试认证路由
        auto test_route2 = gateway.findRoute("POST", "/api/v1/auth/register");
        if (test_route2) {
            LOG_INFO("✓ POST /api/v1/auth/register 匹配到路由: " + test_route2->service_name);
        } else {
            LOG_ERROR("✗ POST /api/v1/auth/register 未找到匹配路由");
        }

        // 测试游戏认证路由
        auto test_route3 = gateway.findRoute("POST", "/api/v1/game/login");
        if (test_route3) {
            LOG_INFO("✓ POST /api/v1/game/login 匹配到路由: " + test_route3->service_name);
        } else {
            LOG_ERROR("✗ POST /api/v1/game/login 未找到匹配路由");
        }

        // 测试Snake游戏路由
        auto test_route4 = gateway.findRoute("GET", "/api/v1/snake/rooms");
        if (test_route4) {
            LOG_INFO("✓ GET /api/v1/snake/rooms 匹配到路由: " + test_route4->service_name);
        } else {
            LOG_ERROR("✗ GET /api/v1/snake/rooms 未找到匹配路由");
        }

        // 测试Snake游戏统计路由
        auto test_route5 = gateway.findRoute("GET", "/api/v1/snake/stats");
        if (test_route5) {
            LOG_INFO("✓ GET /api/v1/snake/stats 匹配到路由: " + test_route5->service_name);
        } else {
            LOG_ERROR("✗ GET /api/v1/snake/stats 未找到匹配路由");
        }

        // 6. 等待服务自动注册
        LOG_DEBUG("等待各服务自动注册...");
        LOG_DEBUG("认证服务将在启动后自动注册到API网关");
        LOG_DEBUG("  - 支持的端点: /api/v1/auth/*, /api/v1/game/*");
        LOG_DEBUG("Snake游戏服务将在启动后自动注册到API网关");
        LOG_DEBUG("  - 支持的端点: /api/v1/snake/*");

        // 注意：服务实例将在各服务启动时自动注册，无需手动添加模拟实例

        // 7. 验证配置完整性
        LOG_DEBUG("验证系统配置...");

        // 显示关键路由信息
        LOG_DEBUG("关键路由配置:");
        LOG_DEBUG("认证服务路由 (localhost:8008):");
        LOG_DEBUG("  - POST /api/v1/auth/register -> 用户注册");
        LOG_DEBUG("  - POST /api/v1/auth/login -> 用户登录");
        LOG_DEBUG("  - POST /api/v1/game/login -> 游戏登录认证");
        LOG_DEBUG("  - GET /api/v1/game/servers -> 获取游戏服务器列表");
        LOG_DEBUG("Snake游戏服务路由 (localhost:8084):");
        LOG_DEBUG("  - GET /api/v1/snake/rooms/public -> 获取公开房间列表");
        LOG_DEBUG("  - GET /api/v1/snake/leaderboard -> 获取排行榜");
        LOG_DEBUG("  - GET /api/v1/snake/stats -> 获取游戏统计");
        LOG_DEBUG("  - GET /api/v1/snake/config -> 获取游戏配置");

        // 8. 启动网关
        LOG_INFO("启动API网关...");
        gateway.start();

        LOG_INFO("API网关启动完成，监听端口: 8080");
        LOG_DEBUG("健康检查: http://localhost:8080/health");
        LOG_DEBUG("服务统计: http://localhost:8080/api/v1/services/stats");
        LOG_DEBUG("");
        LOG_DEBUG("API测试命令:");
        LOG_DEBUG("认证服务测试:");
        LOG_DEBUG("  curl -X POST http://localhost:8080/api/v1/auth/register -H 'Content-Type: application/json' -d '{\"username\":\"test\",\"password\":\"test123\",\"email\":\"test@example.com\"}'");
        LOG_DEBUG("  curl -X POST http://localhost:8080/api/v1/auth/login -H 'Content-Type: application/json' -d '{\"username\":\"test\",\"password\":\"test123\"}'");
        LOG_DEBUG("游戏认证测试:");
        LOG_DEBUG("  curl -X POST http://localhost:8080/api/v1/game/login -H 'Content-Type: application/json' -H 'Authorization: Bearer <token>' -d '{\"game_type\":\"snake\"}'");
        LOG_DEBUG("  curl -X GET http://localhost:8080/api/v1/game/servers?game_type=snake -H 'Authorization: Bearer <token>'");
        LOG_DEBUG("Snake游戏服务测试:");
        LOG_DEBUG("  curl -X GET http://localhost:8080/api/v1/snake/rooms/public");
        LOG_DEBUG("  curl -X GET http://localhost:8080/api/v1/snake/leaderboard");
        LOG_DEBUG("  curl -X GET http://localhost:8080/api/v1/snake/stats");

        LOG_INFO("API网关启动成功，按任意键停止...");
        std::cin.get();

        // 8. 停止网关
        gateway.stop();

    } catch (const std::exception& e) {
        LOG_ERROR("API网关运行失败: " + std::string(e.what()));
        return 1;
    }

    return 0;
}